package com.xiaoyu.lanling.share;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;

import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xiaoyu.base.AppConfig;
import com.xiaoyu.base.app.AppContext;
import com.xiaoyu.base.utils.RxUtils;
import com.xiaoyu.lanling.common.Constant;
import com.xiaoyu.lanling.qqapi.QQEntryActivity;
import com.xiaoyu.lanling.widget.photo.PhotoUtils;

import java.io.File;

import in.srain.cube.util.UTUtil;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

@SuppressLint("CheckResult")
public class ShareController {

    private static final ShareController ourInstance = new ShareController();

    private IWXAPI mIWXAPI;

    public static ShareController getInstance() {
        return ourInstance;
    }

    private ShareController() {
        final Context context = AppContext.getContext();
        mIWXAPI = WXAPIFactory.createWXAPI(context, AppConfig.wechatAppId(), true);
        mIWXAPI.registerApp(AppConfig.wechatAppId());
    }

    public IWXAPI getIWXAPI() {
        return mIWXAPI;
    }

    public void shareText(Context context, String message, ComponentName componentName) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_TEXT, message);
        intent.setType("text/plain");
        intent.setComponent(componentName);
        Intent chooserIntent = Intent.createChooser(intent, "Share");
        if (chooserIntent == null) {
            return;
        }
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(chooserIntent);
    }

    public void shareImage(Context context, String filePath) {
        File file = new File(filePath);
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context, context.getApplicationInfo().packageName
                    + ".file.provider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.setType("image/*");
        Intent chooserIntent = Intent.createChooser(intent, "Share");
        if (chooserIntent == null) {
            return;
        }
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(chooserIntent);
    }

    public void shareImageForImageUrl(Context context, String url) {
        PhotoUtils.downloadImage(url)
                .compose(RxUtils.ioToMainSingleScheduler())
                .filter(file -> file != null && !TextUtils.isEmpty(file.getPath()))
                .filter(file -> context != null)
                .subscribe(file -> shareImage(context, file.getPath()), Throwable::printStackTrace);
    }

    public void shareMessage(Context context, String mobile, String message) {
        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + mobile));
        intent.putExtra("sms_body", message);
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public void shareWeChat(Context context, String text, boolean isMoment) {
        if (!mIWXAPI.isWXAppInstalled()) {
            return;
        }
        //初始化一个 WXTextObject 对象，填写分享的文本内容
        WXTextObject textObj = new WXTextObject();
        textObj.text = text;

        //用 WXTextObject 对象初始化一个 WXMediaMessage 对象
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObj;
        msg.description = text;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "text";
        req.message = msg;
        req.scene = isMoment ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        mIWXAPI.sendReq(req);
    }

    public void shareWeChatForImageUrl(Context context, String url, boolean isMoment) {
        //        if (!mIWXAPI.isWXAppInstalled()) {
        //            return;
        //        }
        //        PhotoUtils.downloadImage(url)
        //                .compose(RxUtils.ioToMainSingleScheduler())
        //                .filter(file -> file != null && !TextUtils.isEmpty(file.getPath()))
        //                .filter(file -> context != null)
        //                .subscribe(file -> {
        //                    WXImageObject wxImageObject = new WXImageObject();
        //                    wxImageObject.setImagePath(file.getPath());
        //
        //                    WXMediaMessage wxMediaMessage = new WXMediaMessage(wxImageObject);
        //                    SendMessageToWX.Req req = new SendMessageToWX.Req();
        //                    req.transaction = "img";
        //                    req.message = wxMediaMessage;
        //                    req.scene = isMoment ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        //                    mIWXAPI.sendReq(req);
        //                }, Throwable::printStackTrace);
    }

    public void shareQQ(Context context, String shareUrl, String title, String text, boolean isQzone) {
        Intent intent = new Intent(context, QQEntryActivity.class);
        intent.putExtra(Constant.ShareConfig.SHARE_QQ_URL_KEY, shareUrl);
        intent.putExtra(Constant.ShareConfig.SHARE_QQ_TITLE_KEY, title);
        intent.putExtra(Constant.ShareConfig.SHARE_QQ_TEXT_KEY, text);
        intent.putExtra(Constant.ShareConfig.SHARE_QQ_IS_QZONE_KEY, isQzone);
        intent.putExtra(Constant.ShareConfig.SHARE_QQ_IMAGE_KEY, Constant.ShareConfig.SHARE_LOGO_URL);
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public void shareQQForImageUrl(Context context, String url, boolean isQzone) {
        PhotoUtils.downloadImage(url)
                .compose(RxUtils.ioToMainSingleScheduler())
                .filter(file -> file != null && !TextUtils.isEmpty(file.getPath()))
                .filter(file -> context != null)
                .subscribe(file -> {
                    Intent intent = new Intent(context, QQEntryActivity.class);
                    intent.putExtra(Constant.ShareConfig.SHARE_QQ_TYPE_KEY, Constant.ShareConfig.SHARE_QQ_TYPE_IMAGE_KEY);
                    intent.putExtra(Constant.ShareConfig.SHARE_QQ_IS_QZONE_KEY, isQzone);
                    intent.putExtra(Constant.ShareConfig.SHARE_QQ_IMAGE_KEY, file.getPath());
                    intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }, Throwable::printStackTrace);
    }

    public void shareWeibo(Context context, String shareUrl, String title, String text) {
        //        Intent intent = new Intent(context, WBEntryActivity.class);
        //        intent.putExtra(Constant.ShareConfig.SHARE_WEIBO_URL_KEY, shareUrl);
        //        intent.putExtra(Constant.ShareConfig.SHARE_WEIBO_TITLE_KEY, title);
        //        intent.putExtra(Constant.ShareConfig.SHARE_WEIBO_TEXT_KEY, text);
        //        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        //        context.startActivity(intent);
    }

    @SuppressLint("InflateParams")
    public void showShareDialog(FragmentActivity activity, String shareUrl, String title, String text) {
        //        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(activity);
        //        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_share_layout, null);
        //        RelativeLayout momentView = view.findViewById(R.id.share_moment_layout);
        //        TextView momentText = view.findViewById(R.id.share_moment_text);
        //        RelativeLayout wechatView = view.findViewById(R.id.share_wechat_layout);
        //        TextView wechatText = view.findViewById(R.id.share_wechat_text);
        //        RelativeLayout qqView = view.findViewById(R.id.share_qq_layout);
        //        TextView qqText = view.findViewById(R.id.share_qq_text);
        //        RelativeLayout qzoneView = view.findViewById(R.id.share_qzone_layout);
        //        TextView qzoneText = view.findViewById(R.id.share_qzone_text);
        //        RelativeLayout systemView = view.findViewById(R.id.share_system_layout);
        //        TextView systemText = view.findViewById(R.id.share_system_text);
        //
        //        momentText.setText(DocData.getInstance().getDoc("mix.share_moment_wechat"));
        //        wechatText.setText(DocData.getInstance().getDoc("mix.share_friend_wechat"));
        //        qqText.setText(DocData.getInstance().getDoc("mix.share_friend_qq"));
        //        qzoneText.setText(DocData.getInstance().getDoc("mix.share_moment_qq"));
        //        systemText.setText(DocData.getInstance().getDoc("mix.share_more"));
        //
        //        momentView.setOnClickListener(view1 -> {
        //            shareWeChat(activity, shareUrl, title, text, true);
        //            logEventForInit("wechat_moment");
        //            bottomSheetDialog.dismiss();
        //        });
        //        wechatView.setOnClickListener(view1 -> {
        //            shareWeChat(activity, shareUrl, title, text, false);
        //            logEventForInit("wechat");
        //            bottomSheetDialog.dismiss();
        //        });
        //        qqView.setOnClickListener(view1 -> {
        //            shareQQ(activity, shareUrl, title, text, false);
        //            logEventForInit("qq");
        //            bottomSheetDialog.dismiss();
        //        });
        //        qzoneView.setOnClickListener(view1 -> {
        //            shareQQ(activity, shareUrl, title, text, true);
        //            logEventForInit("qzone");
        //            bottomSheetDialog.dismiss();
        //        });
        //        systemView.setOnClickListener(view1 -> {
        //            shareText(activity, shareUrl);
        //            logEventForInit("more");
        //            bottomSheetDialog.dismiss();
        //        });
        //
        //        bottomSheetDialog.setContentView(view);
        //        bottomSheetDialog.show();
    }

    private void logEventForInit(String shareWay) {
        Bundle params = new Bundle();
        params.putString("share_way", shareWay);
        UTUtil.getInstance().logEvent("invite", params);
    }
}
